package com.school.empsys.utils;

import java.util.List;
import java.util.Map;

import com.school.empsys.constants.Role;
import com.school.empsys.constants.UserConstants;
import com.school.empsys.model.Permission;
import com.school.empsys.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

public class UserUtil {

    public static User getCurrentUser() {
        User user = (User) getSession().getAttribute(UserConstants.LOGIN_USER);
        return user;
    }

    public static void setUserSession(User user) {
        getSession().setAttribute(UserConstants.LOGIN_USER, user);
    }

    @SuppressWarnings("unchecked")
    public static List<Permission> getCurrentPermissions() {
        List<Permission> list = (List<Permission>) getSession().getAttribute(UserConstants.USER_PERMISSIONS);
        return list;
    }

    public static void setPermissionSession(List<Permission> list) {
        getSession().setAttribute(UserConstants.USER_PERMISSIONS, list);
    }

    public static Session getSession() {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        return session;
    }

    public static boolean hasRole(String role) {
        Subject subject = SecurityUtils.getSubject();
        return subject.hasRole(role);
    }

    public static void setParams(Map<String, Object> params) {
        if (UserUtil.hasRole(Role.ROLE_EMP_USER_CIVILIAN.getName()) || UserUtil.hasRole(Role.ROLE_EMP_USER_SALES.getName())) {
            params.put("userId", UserUtil.getCurrentUser().getId());
        }
    }
}
